use reqwest::Client;
use tracing::debug;

pub struct HttpClient;

impl HttpClient {
    pub async fn send_get(url: String, token: &str) -> Result<String, reqwest::Error> {
        let client = Client::new();

        // 发送 GET 请求
        let response = client
            .get(&url)
            .header("Authorization", format!("Bearer {}", token))
            .send()
            .await?;

        let r = response.text().await?;
        debug!("Response: {:?}", r);
        Ok(r)
    }

    pub async fn send_post(url: String, body: String) -> Result<String, reqwest::Error> {
        let client = Client::new();

        // 发送 POST 请求
        let response = client
            .post(&url)
            .header("Content-Type", "application/x-www-form-urlencoded")
            .body(body)
            .send()
            .await?;

        let r = response.text().await?;
        debug!("Response: {:?}", r);
        Ok(r)
    }
}


#[cfg(test)]
mod tests {
    use std::collections::HashMap;
    use serde_json::Value;
    use tracing::debug;
    use crate::http::http_request::{HttpMethod, HttpVersion};
    use super::*;
    // use tokio::test;
    #[test]
    fn test_send() -> Result<(), Box<dyn std::error::Error>>{

        const GITEE_OAUTH_URL: &str = "https://gitee.com/oauth/token";

        const CODE: &str = "deede528705224c73366f25869930cf34911b1508152e3ca6b89184aefe2d541";

        const GITEE_OAUTH_CLIENT_ID: &str = "b9791c72cab5064926ced23043e0753e273315e47d1644c04a09a1aca8db7c51";

        const GITEE_OAUTH_CLIENT_SECRET: &str = "a4970695ad5c6274122d0cb8f312490ce5eadab080735f7810b79bfc6bdcd368";

        const GITEE_OAUTH_REDIRECT_URI: &str = "http://wujianming.xyz";

        const GITEE_USER_INFO_URL: &str = "https://gitee.com/api/v5/user";

        // let mut req = HttpRequest::new(
        //     HttpMethod::POST,
        //     "/oauth/token".to_string(),
        //     HttpVersion::HTTP11,
        //     HashMap::new(),
        //     HashMap::new(),
        //     String::new(),
        // );
        let body_str = format!("grant_type=authorization_code&code={CODE}&client_id={GITEE_OAUTH_CLIENT_ID}&client_secret={GITEE_OAUTH_CLIENT_SECRET}&redirect_uri={GITEE_OAUTH_REDIRECT_URI}");

        // req.body = body_str.clone();
        //
        //
        let headers = HashMap::from([
            ("Content-Type".to_string(), "application/x-www-form-urlencoded".to_string()),
            ("Accept".to_string(), "*/*".to_string()),
            ("Accept-Encoding".to_string(), "gzip, deflate, br".to_string()),
            ("user-agent".to_string(), "Rust-http-client".to_string()),
            ("Host".to_string(), "gitee.com".to_string()),
            ("Connection".to_string(), "keep-alive".to_string()),
            ("Cache-Control".to_string(), "no-cache".to_string()),
            ("Content-Length".to_string(), body_str.len().to_string())
        ]);
        //
        // req.headers = headers;

        // let response = HttpClient::send("https://gitee.com".to_string(), req);

        let client = reqwest::blocking::Client::new();

        // 发送 POST 请求
        let response = client
            .post(GITEE_OAUTH_URL)
            .header("Content-Type", "application/x-www-form-urlencoded")
            .body(body_str)
            .send()?;


        let r   = response.text()?;

        println!("Response: {:?}", r);

        let token_response: Value  = serde_json::from_str(r.as_str())?;
        //
        println!("Response: {:?}", token_response["access_token"]);



        // let response_get = HttpClient::send_get(GITEE_USER_INFO_URL.parse().unwrap(), &"a880ab9e553a0291ef4a9214467748a3".to_string());

        // let user_info: Value = serde_json::from_str(response_get.as_str())?;

        // println!("oauth2_handler Response_get: id: {:?} name: {:?} avatar_url: {:?}", user_info["id"], user_info["name"], user_info["avatar_url"]);

        Ok(())
    }
}